package com.drug.mingkang.controller;

import com.alibaba.druid.util.StringUtils;
import com.drug.mingkang.model.HqDrug;
import com.drug.mingkang.model.HqDrugtype;
import com.drug.mingkang.model.Specification;
import com.drug.mingkang.model.vo.ExcelDataVO;
import com.drug.mingkang.model.vo.HqDrugVo;
import com.drug.mingkang.permission.model.PerUsers;
import com.drug.mingkang.service.HqDrugService;
import com.drug.mingkang.utils.EarlyWarning;
import com.drug.mingkang.utils.ResponseMessage;
import com.drug.mingkang.utils.Tools;
import com.drug.mingkang.utils.excel.ExcelReader;
import com.drug.mingkang.utils.excel.ExcelWriter;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import static com.drug.mingkang.utils.excel.ExcelWriter.buildDataSheet;

/**
 * 药品表(HqDrug)表控制层
 *
 * @author liudan
 * @since 2020-08-11 12:00:12
 */
@Api(value = "药品表控制层",tags = "药品Contorller")
@RestController
@RequestMapping("hqDrug")
public class HqDrugController {
    /**
     * 服务对象
     */
    @Resource
    private HqDrugService hqDrugService;

    @Resource
    HttpSession session;

    @Resource
    private Tools tools;

    ResponseMessage responseMessage = new ResponseMessage();

    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @RequestMapping("selectOne")
    public HqDrug selectOne(String id) {
        return this.hqDrugService.queryById(id);
    }

    /**
     * 查询多条数据
     *
     * @return 对象列表
     */
    @RequestMapping("selectAll")
    public Map<String,Object> selectAll(HqDrug drug){
        List<HqDrug> list = hqDrugService.findEvery(drug);
        int count = hqDrugService.findEveryCount(drug);
        Tools tools = new Tools();
        return tools.limit(list,count);
    }

    @RequestMapping("selectAlls")
    public Map<String,Object> selectAlls(HqDrug drug){

        PerUsers perUsers = (PerUsers) session.getAttribute("perUsers");
        String companyId = perUsers.getCompanyId();

        List<HqDrug> list = hqDrugService.findEverys(drug,companyId);
        int count = hqDrugService.findEveryCounts(drug,companyId);
        Tools tools = new Tools();
        return tools.limit(list,count);
    }

    /**
     * 查询药品库存预警数量
     * @param hqDrug
     * @return
     */
    @PostMapping("findDrugWarning")
    public Map<String,Object> findDrugWarning(HqDrug hqDrug){
        hqDrug.setWarningNum(EarlyWarning.ZGS_YPKCYJ);
        List<HqDrug> list = this.hqDrugService.findDrugWarning(hqDrug);

        int count = this.hqDrugService.findDrugWarningCount(hqDrug);


        return tools.limit(list,count);
    }

    /**
     * 关联查询多条数据及其药品类型名称
     *
     * @return 对象列表
     */
    @RequestMapping("selectAllTwo")
    public Map<String,Object> selectAllTwo(HqDrug drug){
        List<HqDrug> list = hqDrugService.queryAllByType(drug);
        int count = hqDrugService.selectCount(drug);
        Tools tools = new Tools();
        return tools.limit(list,count);
    }

    /**
     * 查询药品类型
     * @return 对象列表
     */
    @RequestMapping("selectType")
    public List<HqDrugtype> selectType(){
        List<HqDrugtype> hqDrugtypes = this.hqDrugService.selectByType();
        return hqDrugtypes;
    }

    /**
     * 增加或者修改药品
     * @param hqDrug 药品类
     * @param file 图片
     * @return 信息类
     */
    @RequestMapping("addOrUpdate")
    public ResponseMessage addOrUpdate(HqDrug hqDrug, MultipartFile file,Specification specification){
        HqDrug hqDrug1 = new HqDrug();
        if(StringUtils.isEmpty(hqDrug.getDrugId())) {
            System.out.println("增加");
            hqDrug1= hqDrugService.insert(hqDrug,file,specification);
        }else{
            hqDrug1=hqDrugService.update(hqDrug,file);
        }
        if(!StringUtils.isEmpty(hqDrug1.getDrugId())){
            responseMessage.setStatus(1);
            responseMessage.setMessage("提交成功");
        }
        return responseMessage;
    }

    /**
     * 根据药品id查询说明书
     * @param id 药品id
     * @return 实例对象
     */
    @RequestMapping("selectSpec")
   public Specification selectSpec(String id){
        return this.hqDrugService.queryBySpe(id);
   }

    /**
     * 修改说明书
     * @param specification
     * @return
     */
   @RequestMapping("updateSep")
   public ResponseMessage updateSep(Specification specification){
        Specification specification1 = this.hqDrugService.updateSep(specification);
        if (specification1.getSpId()==null){
            responseMessage.setStatus(0);
            responseMessage.setMessage("提交失败");
        }else{
            responseMessage.setStatus(1);
            responseMessage.setMessage("提交成功");
        }
        return responseMessage;
   }

    /**
     * 根据药品id删除此药品
     * @param drugId 药品id
     * @return
     */
    @RequestMapping("delete")
   public ResponseMessage delete(String drugId){
       boolean b = this.hqDrugService.deleteById(drugId);
       if (b){
           responseMessage.setStatus(1);
           responseMessage.setMessage("删除成功");
       }else{
           responseMessage.setStatus(0);
           responseMessage.setMessage("已加入生省计划不可以删除");
       }
       return responseMessage;
   }

   @GetMapping("findAll")
   public Map<String,Object> findAll(HqDrugVo hqDrugVo){

       List<HqDrug> list = hqDrugService.fqueryAll(hqDrugVo);
       int count = hqDrugService.fcount(hqDrugVo);
       Map<String, Object> map = tools.limit(list,count);
       return map;
   }


    /**
     * 通过实体作为筛选条件查询
     * @param hqDrugVo
     * @return
     */
    @ApiOperation(value = "查询所有药品",notes = "查询所有药品",httpMethod = "POST",response = Map.class)
    @PostMapping("fqueryAll")
    public Map<String,Object> fqueryAll(HqDrugVo hqDrugVo){

        List<HqDrug> list = hqDrugService.fqueryAll(hqDrugVo);
        int count = hqDrugService.fcount(hqDrugVo);
        Map<String, Object> map = tools.limit(list,count);
        return map;
    }

    /**
     * 修改审核状态
     * @param drugId
     * @return
     */
    @PostMapping("updateReviewState")
    public ResponseMessage updateReviewState(String drugId){
        int rows = hqDrugService.fupdate(drugId);
        return rows > 0 ? ResponseMessage.success("操作成功") : ResponseMessage.error("操作失败");
    }

    /**
     * 药品数据导出及其模板下载
     * @param excelDataVO
     * @param response
     * @throws UnsupportedEncodingException
     */
    @RequestMapping("poiExcel")
    public void poiExcel(String excelDataVO, HttpServletResponse response) throws UnsupportedEncodingException {
        SimpleDateFormat formatter= new SimpleDateFormat("yyyy-MM-dd 'at' HH:mm:ss");
        Date date = new Date(System.currentTimeMillis());
        String format = formatter.format(date);

        Workbook workbook ;
        String filename ;
        //没有传入数据是下载模板
        if (StringUtils.isEmpty(excelDataVO)){
            // 生成xlsx的Excel
            workbook = new SXSSFWorkbook();

            // 生成Sheet表，写入第一行的列头
            buildDataSheet(workbook);

            filename = "template__"+format+".xlsx";
        }else{
            Gson gson = new Gson();
            // 取到需要写入的数据列表
            List<ExcelDataVO> dataVOList = gson.fromJson(excelDataVO,new TypeToken<List<ExcelDataVO>>(){}.getType());

            // 写入数据到工作簿对象内
            workbook = ExcelWriter.exportData(dataVOList);

            filename = format+".xlsx";
        }

        try {
            response.setContentType("application/vnd.ms-excel");
            response.setHeader("Content-Disposition", "attachment; filename=\""+ filename + "\"");
            workbook.write(response.getOutputStream());

        } catch (Exception e) {
            System.out.println(("输出Excel时发生错误，错误原因：" + e.getMessage()));
        } finally {
            try {
                if (null != workbook) {
                    workbook.close();
                }
            } catch (IOException e) {
                System.out.println(("关闭输出流时发生错误，错误原因：" + e.getMessage()));
            }
        }
    }

    /**
     * 药品数据导入
     * @param file
     * @return
     */
    @PostMapping("introExcel")
    public ResponseMessage introExcel(MultipartFile file) {
        // 读取Excel文件内容
        List<ExcelDataVO> readResult = ExcelReader.readExcel(file);
        List<String> list = new ArrayList<>();
        //将类型名字加入list集合中
        for (ExcelDataVO v : readResult){
            list.add(v.getTypeName());
        }
        //根据类型名称批量查询类型id
        List<HqDrugtype> hqDrugtypes = this.hqDrugService.getItermByList(list);
        //将对应的类型id给予对应的类型
        for (int i = 0; i < readResult.size(); i++) {
            for (int j = 0; j < hqDrugtypes.size(); j++) {
                if (readResult.get(i).getTypeName().equals(hqDrugtypes.get(j).getTypeName())){
                    readResult.get(i).setTypeId(hqDrugtypes.get(j).getTypeId());
                }
            }
        }
        //当ExcelDataVO中有类型id为null时则返回类型不正确
        for (ExcelDataVO v : readResult){
            if (StringUtils.isEmpty(v.getTypeId())){
                return ResponseMessage.error("传入类型不正确");
            }
        }
        //批量增加
        int rows = this.hqDrugService.insertBatch(readResult);
        return rows > 0 ? ResponseMessage.success("导入成功") : ResponseMessage.error("传入格式不正确");
    }


    /**
     * 查询小于库存预警的药品
     * @param hqDrugVo
     * @param session
     * @return
     */
    @PostMapping("addPurchasePlan")
    public Map<String,Object> addPurchasePlan(HqDrugVo hqDrugVo, HttpSession session){

        PerUsers perUsers = (PerUsers)session.getAttribute("perUsers");

        hqDrugVo.setImmId(perUsers.getCompanyId());
        hqDrugVo.setCount(EarlyWarning.FGS_YPKCYJ);

        List<HqDrug> list = hqDrugService.addPurchasePlan(hqDrugVo);
        int count = hqDrugService.addPurchasePlanCount(hqDrugVo);
        Map<String, Object> map = tools.limit(list,count);
        return map;

    }

}